package com.pocket.insight.base.config;

import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/12/2
 */
// https://blog.csdn.net/sfh2018/article/details/116594698
@Order(2)
@Slf4j
@Component
@WebFilter(urlPatterns = {"/*"}, filterName = "corsFilter")
public class CorsFilter extends OncePerRequestFilter {

    private static List<String>         allowOrigin;

    static {
        allowOrigin = List.of("localhost:3000");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestOrigin = request.getHeader("origin");
        log.debug("过滤器【CORS】：请求【{}】Origin：{}", request.getRequestURI(), Optional.ofNullable(requestOrigin).orElse(""));
        if (CollectionUtils.isNotEmpty(allowOrigin)) {
            if (StringUtils.isNotBlank(requestOrigin)) {
                for (String origin : allowOrigin) {
                    if (requestOrigin.endsWith(origin)) {
                        response.setHeader("Access-Control-Allow-Origin", requestOrigin);
                        log.debug("过滤器【CORS】：添加 Access-Control-Allow-Origin：{}", requestOrigin);
                        break;
                    }
                }
            }

            response.setHeader("Access-Control-Allow-Headers", "accept,content-type,referer,sec-ch-ua,sec-ch-ua-mobile,ec-ch-ua-platform,user-agent");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Private-Network", "true");
            response.setHeader("Access-Control-Max-Age", "3600");
            //response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            //response.setHeader("Pragma", "no-cache");
            response.setCharacterEncoding("UTF-8");
            filterChain.doFilter(request, response);
        }
    }
}